// 血压自动测量设置页面
import { getBPLAutoMeasureSettings, saveBPLAutoMeasureSettings } from '../../../utils/api/BPLControl';

Page({
  data: {
    // 自动测量开关
    autoMeasureEnabled: true,

    // 测量间隔
    dayInterval: 30, // 白天测量间隔（分钟）
    nightInterval: '', // 夜间测量间隔

    // 夜间测量时段
    startTime: '22:00',
    endTime: '结束时间',

    // 选择器显示状态
    showDayIntervalPicker: false,
    showNightIntervalPicker: false,
    showTimePicker: false,
    timePickerTitle: '',
    timePickerType: '', // 'start' | 'end'

    // 选择器选项
    dayIntervalOptions: [
      { text: '15分钟', value: 15 },
      { text: '30分钟', value: 30 },
      { text: '45分钟', value: 45 },
      { text: '60分钟', value: 60 },
      { text: '90分钟', value: 90 },
      { text: '120分钟', value: 120 }
    ],

    nightIntervalOptions: [
      { text: '30分钟', value: '30分钟' },
      { text: '60分钟', value: '60分钟' },
      { text: '90分钟', value: '90分钟' },
      { text: '120分钟', value: '120分钟' },
      { text: '180分钟', value: '180分钟' }
    ],
    currentDate: '12:00',
    minHour: 0,
    maxHour: 24,
  },

  onLoad() {

    this.loadTempSettings();
    this.loadSettings();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadSettings();
  },



  /**
   * 加载临时设置数据（用户上次未保存的输入）
   */
  loadTempSettings() {
    try {
      const tempSettings = wx.getStorageSync('bplAutoMeasureTemp');
      if (tempSettings) {
        this.setData({
          autoMeasureEnabled: tempSettings.autoMeasureEnabled || false,
          dayInterval: tempSettings.dayInterval || 30,
          nightInterval: tempSettings.nightInterval || '',
          startTime: tempSettings.startTime || '22:00',
          endTime: tempSettings.endTime || '结束时间'
        });

        // 清除临时数据
        wx.removeStorageSync('bplAutoMeasureTemp');
      }
    } catch (error) {
      console.error('加载临时数据失败:', error);
    }
  },

  /**
   * 加载设置数据
   */
  async loadSettings() {
    try {
      wx.showLoading({ title: '加载中...' });

      // 先从服务器获取设置
      const result: any = await getBPLAutoMeasureSettings();

      if (result.code === 200 && result.data) {
        const settings = result.data;
        this.setData({
          autoMeasureEnabled: settings.autoMeasureEnabled || false,
          dayInterval: settings.dayInterval || 30,
          nightInterval: settings.nightInterval || '',
          startTime: settings.startTime || '22:00',
          endTime: settings.endTime || '结束时间'
        });
      } else {
        // 如果服务器没有数据，尝试从本地存储加载
        const localSettings = wx.getStorageSync('bplAutoMeasureSettings');
        if (localSettings) {
          this.setData({
            autoMeasureEnabled: localSettings.autoMeasureEnabled || false,
            dayInterval: localSettings.dayInterval || 30,
            nightInterval: localSettings.nightInterval || '',
            startTime: localSettings.startTime || '22:00',
            endTime: localSettings.endTime || '结束时间'
          });
        }
      }

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      console.error('加载设置失败:', error);

      // 发生错误时从本地存储加载
      try {
        const settings = wx.getStorageSync('bplAutoMeasureSettings');
        if (settings) {
          this.setData({
            autoMeasureEnabled: settings.autoMeasureEnabled || false,
            dayInterval: settings.dayInterval || 30,
            nightInterval: settings.nightInterval || '',
            startTime: settings.startTime || '22:00',
            endTime: settings.endTime || '结束时间'
          });
        }
      } catch (storageError) {
        console.error('从本地存储加载设置失败:', storageError);
      }
    }
  },

  /**
   * 自动测量开关变化
   */
  onAutoMeasureChange(event: WechatMiniprogram.SwitchChange) {
    const { detail } = event;
    this.setData({
      autoMeasureEnabled: detail
    });

    if (!detail) {
      // 关闭自动测量时，清空相关设置
      this.setData({
        nightInterval: '',
        endTime: '结束时间'
      });
    }
  },

  /**
   * 选择白天测量周期
   */
  onSelectDayInterval() {
    if (!this.data.autoMeasureEnabled) return;

    this.setData({
      showDayIntervalPicker: true
    });
  },

  /**
   * 白天测量周期确认
   */
  onDayIntervalConfirm(event: any) {
    const { detail } = event;
    const selectedOption = detail.value;

    this.setData({
      dayInterval: selectedOption.value,
      showDayIntervalPicker: false
    });
  },

  /**
   * 关闭白天测量周期选择器
   */
  closeDayIntervalPicker() {
    this.setData({
      showDayIntervalPicker: false
    });
  },

  /**
   * 选择夜间测量周期
   */
  onSelectNightInterval() {
    if (!this.data.autoMeasureEnabled) return;

    this.setData({
      showNightIntervalPicker: true
    });
  },

  /**
   * 夜间测量周期确认
   */
  onNightIntervalConfirm(event: any) {
    const { detail } = event;
    const selectedOption = detail.value;

    this.setData({
      nightInterval: selectedOption.value,
      showNightIntervalPicker: false
    });
  },

  /**
   * 关闭夜间测量周期选择器
   */
  closeNightIntervalPicker() {
    this.setData({
      showNightIntervalPicker: false
    });
  },

  /**
   * 选择开始时间
   */
  onSelectStartTime() {
    if (!this.data.autoMeasureEnabled) return;

    this.setData({
      showTimePicker: true,
      timePickerTitle: '选择开始时间',
      timePickerType: 'start'
    });
  },

  /**
   * 选择结束时间
   */
  onSelectEndTime() {
    if (!this.data.autoMeasureEnabled) return;

    this.setData({
      showTimePicker: true,
      timePickerTitle: '选择结束时间',
      timePickerType: 'end'
    });
  },

  /**
   * 时间确认
   */
  onTimeConfirm(event: any) {
    const { detail } = event;
    console.log(detail)

    if (this.data.timePickerType === 'start') {
      this.setData({
        startTime: detail
      });
    } else if (this.data.timePickerType === 'end') {
      this.setData({
        endTime: detail
      });
    }

    this.setData({
      showTimePicker: false,
      timePickerType: ''
    });
  },

  /**
   * 关闭时间选择器
   */
  closeTimePicker() {
    this.setData({
      showTimePicker: false,
      timePickerType: ''
    });
  },

  /**
   * 验证设置
   */
  validateSettings(): boolean {
    const { autoMeasureEnabled, nightInterval, endTime, startTime } = this.data;

    if (autoMeasureEnabled) {
      if (!nightInterval) {
        wx.showToast({
          title: '请选择夜间测量周期',
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      if (endTime === '结束时间') {
        wx.showToast({
          title: '请选择结束时间',
          icon: 'none',
          duration: 2000
        });
        return false;
      }

      // 验证时间逻辑合理性
      const startHour = parseInt(startTime.split(':')[0]);
      const endHour = parseInt(endTime.split(':')[0]);

      // 夜间时段应该跨越午夜，开始时间应该大于结束时间
      if (startHour <= endHour) {
        wx.showToast({
          title: '夜间时段设置有误，结束时间应该在第二天',
          icon: 'none',
          duration: 3000
        });
        return false;
      }
    }

    return true;
  },

  /**
   * 保存设置
   */
  async onSave() {
    if (!this.validateSettings()) {
      return;
    }

    try {
      wx.showLoading({
        title: '保存中...'
      });

      const settings = {
        autoMeasureEnabled: this.data.autoMeasureEnabled,
        dayInterval: this.data.dayInterval,
        nightInterval: this.data.nightInterval,
        startTime: this.data.startTime,
        endTime: this.data.endTime,
        updateTime: new Date().toISOString()
      };

      // 保存到本地存储
      wx.setStorageSync('bplAutoMeasureSettings', settings);

      // 保存到服务器
      try {
        await this.saveSettingsToServer(settings);
      } catch (serverError) {
        console.warn('服务器保存失败，但本地保存成功:', serverError);
        // 即使服务器保存失败，也提示保存成功（本地已保存）
      }

      wx.hideLoading();

      // 显示保存成功的提示
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });

      // 触发页面刷新事件（如果有父页面监听）
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage && prevPage.onBPLAutoMeasureSettingsChanged) {
        prevPage.onBPLAutoMeasureSettingsChanged(settings);
      }

      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);

    } catch (error) {
      wx.hideLoading();
      console.error('保存设置失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  },

  /**
   * 保存设置到服务器
   */
  async saveSettingsToServer(settings: any): Promise<void> {
    try {
      const result: any = await saveBPLAutoMeasureSettings(settings);
      if (result.code !== 200) {
        throw new Error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存到服务器失败:', error);
      throw error;
    }
  },

  /**
   * 页面卸载时保存临时数据
   */
  onUnload() {
    // 保存用户当前的输入状态
    const tempSettings = {
      autoMeasureEnabled: this.data.autoMeasureEnabled,
      dayInterval: this.data.dayInterval,
      nightInterval: this.data.nightInterval,
      startTime: this.data.startTime,
      endTime: this.data.endTime
    };

    try {
      wx.setStorageSync('bplAutoMeasureTemp', tempSettings);
    } catch (error) {
      console.error('保存临时数据失败:', error);
    }
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    try {
      await this.loadSettings();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      });
    } catch (error) {
      wx.showToast({
        title: '刷新失败',
        icon: 'none',
        duration: 1000
      });
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 格式化时间显示
   */
  formatTimeDisplay(time: string): string {
    if (time === '结束时间') {
      return time;
    }
    // 确保时间格式为 HH:MM
    const parts = time.split(':');
    if (parts.length === 2) {
      const hours = parts[0].padStart(2, '0');
      const minutes = parts[1].padStart(2, '0');
      return `${hours}:${minutes}`;
    }
    return time;
  },

  /**
   * 获取设置摘要（用于调试）
   */
  getSettingsSummary(): string {
    const { autoMeasureEnabled, dayInterval, nightInterval, startTime, endTime } = this.data;

    if (!autoMeasureEnabled) {
      return '自动测量已关闭';
    }

    return `自动测量: 开启
白天周期: ${dayInterval}分钟 (6:00-22:00)
夜间周期: ${nightInterval} (${startTime}-${endTime})`;
  }
});